package boun.center;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CmpeNewsFetcher {
	private static final int NEWS_LIMIT = 5;
	private static final String CHARSET = "ISO-8859-9";

    public static ArrayList<CmpeNews> fetchCmpeNews() throws IOException, ParseException {
        String webContent = WebDownloader.fetchWebContent("http://www.cmpe.boun.edu.tr/announcements/", CHARSET);
        return parseCmpeNews(webContent);
    }
	
	private static ArrayList<CmpeNews> parseCmpeNews(String content) throws IOException, ParseException {
		ArrayList<CmpeNews> res = new ArrayList<CmpeNews>();
		Pattern innerTablePattern = Pattern.compile("<table cellpadding=5 cellspacing=0 border=0>\\s*?\\s*?(.*?)\\s*?\\s*?</table>");

		Pattern rowPattern = Pattern.compile("<tr>\\s*?<td>\\s*?<a href=(.*?)>\\s*?<b>\\s*?(.*?)\\s*?</b>\\s*?</a>\\s*?</td>\\s*?</tr>");
		Matcher matcher = innerTablePattern.matcher(content);
		if (matcher.find()) {
			String innerContent = matcher.group(1).trim();
			matcher = rowPattern.matcher(innerContent);
			int i = 0;
			while (matcher.find() && i < NEWS_LIMIT) {
				String url = matcher.group(1).trim();
				String subject = Util.sanifyString(matcher.group(2));
				CmpeNews cmpeNews = getNewsContent(url);
				cmpeNews.setUrl(url);
				cmpeNews.setSubject(subject);
				res.add(cmpeNews);
				++i;
			}
		}
		return res;
	}
	
	private static CmpeNews getNewsContent(String url) throws IOException, ParseException {
		if (url.startsWith("http://www.cmpe.boun.edu.tr/announcements/index.php?id=")) {
			String content = WebDownloader.fetchWebContent(url, CHARSET);
			Pattern textPattern = Pattern.compile("<hr class=baslik2><p>(.*?)</p>.*?<font color=gray>added on <b>(.*?)</b>");
			Matcher matcher = textPattern.matcher(content);
			if (matcher.find()) {
			    CmpeNews result = new CmpeNews();
			    result.setContent(Util.sanifyString(matcher.group(1)));
			    String dateString = matcher.group(2).trim();
			    
			    //19 Oct '11
                Calendar cal = Calendar.getInstance();
                SimpleDateFormat sdf = new SimpleDateFormat("d MMM ''yy", Locale.US);
                cal.setTime(sdf.parse(dateString));
			    
			    result.setCreationDate(cal);
				return result;
			} else {
				return null;
			}
		} else {
			return null;
		}
	}
}
